package cn.ipanel.bigdata.job.basic

import cn.ipanel.bigdata.boot.Job
import cn.ipanel.bigdata.boot.config.{ConfigKey, Configuration}
import cn.ipanel.bigdata.boot.logger.Logger
import cn.ipanel.bigdata.dw.dim.phoenix.{T_AREA, T_HOME => S}
import cn.ipanel.bigdata.dw.dws.{T_HOME_CT => T}
import cn.ipanel.bigdata.utils.Dictionary.{F_STATUS, BusState}
import com.alibaba.fastjson.{JSON, JSONArray}
import org.apache.spark.sql.functions.{col, count, lit, substring, when}
import scalaj.http.Http

import scala.collection.mutable.ListBuffer


/**
 * 家庭按区域统计
 */
class HomeCt extends Job {

  override def onStartup(): Unit = {
    calByDay()
    calByMonth()
  }


  def calByDay(): Unit = {
    T.deleteByPeriodTime(_DAY.toSimpleDate)

    T.save(
      S.load
        .filter(
          substring(col(S.F_REGION), 1, 6) === lit(Configuration.getParam(ConfigKey.ROOT_AREA_CODE).substring(0, 6))
          and col(S.F_CREATE_TIME) < lit(_DAY.next().printFormat("yyyy-MM-dd"))
            and col(F_STATUS) =!= lit(BusState.DEL)
        )
        .select(S.F_HOME_ID, S.F_REGION)
        .groupBy(S.F_REGION)
        .agg(
          count(S.F_HOME_ID) as T.F_HOME_NUM
        )
        .withColumn(T.F_PERIOD_TIME, lit(_DAY.toSimpleDate))
    )
  }

  def calByMonth(): Unit = {
    val thisMonth = _DAY.asMonth
    val nextMonth = thisMonth.next()

    T.deleteByPeriodTime(_DAY.toSimpleMonth)
    T.save(
      S.load
        .filter(
          substring(col(S.F_REGION), 1, 6) === lit(Configuration.getParam(ConfigKey.ROOT_AREA_CODE).substring(0, 6))
          and col(S.F_CREATE_TIME) < lit(nextMonth.printFormat("yyyy-MM-dd"))
            // 当月非删除状态；或虽然是删除状态，但在当月之后删除的
            and (col(F_STATUS) =!= lit(BusState.DEL) or ((col(F_STATUS) === lit(BusState.DEL)) and (col(S.F_UPDATE_TIME) >= lit(thisMonth.printFormat()))))
        )
        .select(S.F_HOME_ID, S.F_REGION)
        .groupBy(S.F_REGION)
        .agg(
          count(S.F_HOME_ID) as T.F_HOME_NUM
        )
        .withColumn(T.F_PERIOD_TIME, lit(thisMonth.toSimpleMonth))
    )
  }


}
